<?php

namespace app\common\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;
use think\facade\Log;
use think\Db;
use app\common\library\Config;
use think\helper\Time;

class Project extends Command
{


    //命令描述
    protected function configure()
    {
        $this->setName('Project')->setDescription('work time run and wx');
    }

    //所要执行的命令
    protected function execute(Input $input, Output $output)
    {
        //开始发送
        // Cache::clear();
        Config::config();
        cache('run_status', 'no');
        //

//        exit;
        if (cache('run_status') == 'no') {
            cache('run_status', 'yes');
            $output->writeln("stories run start");
            $ulist = DB::name('product_run')
                ->where('status', 1)
                ->where('product_id', 10)
                ->where('e_time', '>=', time())
                ->cache(43200)//约12小时
                ->select();
            if (cache('last_time') < time()) {
                //30分钟进行一次
                $output->writeln("project  run ");
                $this->project($ulist);//项目时间计算
                $output->writeln("day_user  run ");
                $this->day_user($ulist);//每日工作时间
                $output->writeln("work_time run ");
                $this->work_time($ulist);//计算本月分配的工时
                $this->stories($ulist);//实际工作时间
                cache('last_time', time() + 60 * 30);
            } else {
                $output->writeln("user no run ");
            }
          //  $output->writeln("last_time_d:" . cache('last_time_d') . '-new_time:' . time());
            if (cache('last_time_d') < time()) {
                //1小时一次
                $output->writeln("clear  run ");
                $output->writeln("project_user_clear  run ");
                $this->project_user_clear($ulist);//清理项目退出用户
                $output->writeln("wx_msg_clear  run ");
                $this->wx_msg_clear($ulist);//清理微信模板消息
                $output->writeln("log  in_wage  run ");
                $this->login_wage($ulist);//计算考勤奖金
                $output->writeln("user  run ");
                $this->user($ulist);//用户工资核算
                cache('last_time_d', time() + 86400 / 24);
            } else {
                $output->writeln("clear no run ");
            }
            $output->writeln("wx_menu run ");
            //发布菜单
            $this->wx_menu($ulist);
            $output->writeln("wx_send  run ");
            $this->wx_send($ulist);//推送微信消息
            $this->wx_fsend($ulist);//推送微信消息
            cache('run_status', 'no');
        } else {
            $output->writeln("task runing ");
        }
        $output->writeln("work time run and wx  over");
    }


    function dbconfig($id)
    {
        return [
            'type' => 'mysql',
            // 服务器地址
            'hostname' => 'rm-2zea426o72962o97z125010.mysql.rds.aliyuncs.com',
            // 数据库名
            'database' => 'u' . $id,
            // 用户名
            'username' => 'weibuyun',
            // 密码
            'password' => 'Wei@#$1209C!=',
        ];
    }

    protected function project_user_clear($ulist)
    {
        foreach ($ulist as $info) {
            $list = DB::connect($this->dbconfig($info['id']))->view('project_user', 'id')
                ->view('auth_group_access', 'uid', 'project_user.uid=auth_group_access.uid')
                ->where('auth_group_access.group_id', 14)
                ->select();
            foreach ($list as $item) {
                DB::connect($this->dbconfig($info['id']))->name('project_user')->where('uid', $item['uid'])->delete();
            }
        }
    }

    protected function wx_fsend($ulist)
    {

        foreach ($ulist as $info2) {
            cache('access_token2', null);
            $tmid = Db::connect($this->dbconfig($info2['id']))->name('config')
                ->where('id', '=', 52)
                ->value('value');
            $run_info = Db::view('product_wx', 'authorizer_access_token')
                ->view('product_run', 'id,domain,diy_domain', 'product_wx.product_run_id=product_run.id')
                ->where('product_run.id', '=', $info2['id'])
                ->find();
            $data['access_token'] = $run_info['authorizer_access_token'];
            $map[] = ['project_financial.financial_type', 'in', '3,4'];
            $map[] = ['project_financial.price', '>', 0];
            $map[] = ['project_financial.remind_time', '<', time() + 86400];
            $map[] = ['project_financial.remind_time', '>', 0];
            $list = Db::connect($this->dbconfig($info2['id']))->view('project_financial', 'id,project_id,project_financial,info,financial_type,c_time,uid,price,remind_time')
                ->view('project', 'title', 'project_financial.project_id=project.id', 'LEFT')
                ->where($map)
                ->whereColumn('project_financial.c_time', '<>', 'project_financial.remind_time')
                // ->fetchSql(true)
                ->select();

            $project_financial = Db::connect($this->dbconfig($info2['id']))->name('config')
                ->where('id', '=', 84)
                ->value('value');
            $array_cfg = preg_split('/[,;\r\n]+/', trim($project_financial, ",;\r\n"));
            if (strpos($project_financial, ':')) {
                $project_financial = [];
                foreach ($array_cfg as $val) {
                    list($k, $v) = explode(':', $val);
                    $project_financial[$k] = $v;
                }
            } else {
                $project_financial = $project_financial;
            }
            $financial_type = Db::connect($this->dbconfig($info2['id']))->name('config')
                ->where('id', '=', 85)
                ->value('value');
            $array_cfg = preg_split('/[,;\r\n]+/', trim($financial_type, ",;\r\n"));
            if (strpos($financial_type, ':')) {
                $financial_type = [];
                foreach ($array_cfg as $val) {
                    list($k, $v) = explode(':', $val);
                    $financial_type[$k] = $v;
                }
            } else {
                $financial_type = $financial_type;
            }
            //找出项目管理员
            $user_list = DB::connect($this->dbconfig($info2['id']))->view('admin', 'openid,id')
                ->view('auth_group_access', 'group_id', 'admin.id=auth_group_access.uid')
                ->where('auth_group_access.group_id', 13)
                ->select();
            foreach ($list as $info) {
                //存入通知列表
//                dump($info);
                $msg['status'] = 2;
                $msg['info'] = $info['title'] . '中财务分类为' . $project_financial[$info['project_financial']] . '，财务类型' . $financial_type[$info['financial_type']];
                $msg['info'] .= '；金额为' . $info['price'] . ';备注' . $info['info'];
                $msg['c_time'] = time();
                $msgid = Db::connect($this->dbconfig($info2['id']))->name('wx_msg')->insertGetID($msg);
                $data['info'] = '提醒时间' . date('Y-m-d  H:i:s', $info['remind_time']) . ';' . $info['info'];
                $data['time'] = date('Y-m-d  H:i:s', time());
                $data['status'] = $financial_type[$info['financial_type']];
                $data['tmid'] = $tmid;
                $data['msg_id'] = $msgid;
                $data['project_name'] = $info['title'];
                $data['info_title'] = $project_financial[$info['project_financial']] . '/金额' . $info['price'];
                foreach ($user_list as $user) {
                    if ($user['openid']) {
                        $data['openid'] = $user['openid'];
                        $data['uid'] = $info['uid'];
                        $data['msgid'] = $this->send($data, 2);
                        //exit;
                        DB::connect($this->dbconfig($info2['id']))->name('wx_msg_info')->strict(false)->insert($data);
                    }

                }
                DB::connect($this->dbconfig($info2['id']))->name('project_financial')->where('id', $info['id'])->update(['c_time' => $info['remind_time']]);
            }

        }
    }


    public function wx_menu($ulist)
    {
        foreach ($ulist as $info2) {
            $list = DB::connect($this->dbconfig($info2['id']))->name('wx_menu')
                ->where('tag_id', 0)
                ->where('up_status', 2)
                ->order('bid asc')
                ->select();
            if ($list) {
                $menu = [];
                $main_menu = 0;
                $wx_button = config('param.wx_button');
                $wx_menu_url = DB::connect($this->dbconfig($info2['id']))->name('wx_menu_url')->select();
                // dump($wx_menu_url);
                //dump($list);
                $run_info = Db::view('product_wx', 'authorizer_access_token')
                    ->view('product_run', 'id,domain,diy_domain', 'product_wx.product_run_id=product_run.id')
                    ->where('product_run.id', '=', $info2['id'])
                    ->find();
                $domain = $run_info['diy_domain'] ? $run_info['diy_domain'] : $run_info['domain'];
                $domain = 'https://' . $domain;
                foreach ($list as $item) {
                    // dump(in_array($item['bid'], [10, 20, 30]));
                    if (in_array($item['bid'], ['b10', 'b20', 'b30'])) {
                        $menu[$main_menu]['name'] = $item['name'];
                        $main_menu = $main_menu + 1;
                    } else {
                        $tmp = [];
                        if ($item['name']) {
                            $tmp['name'] = $item['name'];
                            switch ($item['type']) {
                                case 1:
                                    $tmp['type'] = 'click';
                                    $tmp['key'] = $item['info'];
                                    break;
                                case 2:
                                    $tmp['type'] = 'view';
                                    if ($item['wx_menu_url'] == 0) {
                                        $tmp['url'] = $item['info'];
                                    } else {
                                        $tmp['url'] = $domain . $wx_menu_url[$item['wx_menu_url'] - 1]['url'];
                                    }
                                    break;
                                case 3:
                                    $tmp['type'] = 'scancode_push';
                                    $tmp['key'] = $item['info'];
                                    break;
                                case 4:
                                    $tmp['type'] = 'scancode_waitmsg';
                                    $tmp['url'] = $domain . $item['info'];
                                    break;
                                case 5:
                                    $tmp['type'] = 'pic_sysphoto';
                                    $tmp['key'] = $item['info'];
                                    break;
                                case 6:
                                    $tmp['type'] = 'pic_photo_or_album';
                                    $tmp['key'] = $item['info'];
                                    break;
                                case 7:
                                    $tmp['type'] = 'pic_weixin';
                                    $tmp['key'] = $item['info'];
                                    break;
                                case 8:
                                    $tmp['type'] = 'location_select';
                                    $tmp['key'] = $item['info'];
                                    break;
                                case 9:
                                    $tmp['type'] = 'media_id';
                                    $tmp['media_id'] = $item['info'];
                                    break;
                                case 10:
                                    $tmp['type'] = 'view_limited';
                                    $tmp['media_id'] = $item['info'];
                                    break;
                                case 11:
                                    $tmp['type'] = 'miniprogram';
                                    $tmp['url'] = $item['info'];
                                    $tmp['appid'] = $item['msg'];
                                    $tmp['pagepath'] = 'pages/index/index';
                                    break;
                                default:
                                    $tmp['type'] = 'view';
                                    $tmp['url'] = '';
                            }
                            $menu[$main_menu - 1]['sub_button'][] = $tmp;
                        }
                    }
                }

                if ($list[0]['tag_id'] > 0) {
                    $new['matchrule']['tag_id'] = 0;
                    $url2 = "https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token=" . $run_info['authorizer_access_token'];
                } else {
                    $url2 = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $run_info['authorizer_access_token'];
                }
                //dump($menu);
                $new['button'] = $menu;
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url2);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
                curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($new, JSON_UNESCAPED_UNICODE));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                $tmpInfo = curl_exec($ch);
                if (curl_errno($ch)) {
                    dump(curl_error($ch));
                }
                curl_close($ch);
                $res = json_decode($tmpInfo, true);
                // dump($res);
                if (isset($res['errcode']) && $res['errcode'] == 0) {
                    DB::connect($this->dbconfig($info2['id']))->name('wx_menu')
                        ->where('tag_id', 0)
                        ->where('up_status', 2)
                        ->update(['up_status' => 1]);
                }
            }

        }


    }

    protected function wx_msg_clear($ulist)
    {
        foreach ($ulist as $info) {
            //30天以前的清理掉，微信模板消息
            DB::connect($this->dbconfig($info['id']))->name('wx_msg')->where('c_time', '<', time() - 86400 * 30)->where('status', 2)->delete();
            //考勤365天以前的清理掉，考勤
            DB::connect($this->dbconfig($info['id']))->name('workreg_d')->where('d_time', '<', time() - 86400 * 365)->delete();
            //30天以前的清理掉，定位信息
            DB::connect($this->dbconfig($info['id']))->name('workreg')->where('c_time', '<', time() - 86400 * 30)->delete();
        }

    }

    protected function wx_send($ulist)
    {

        foreach ($ulist as $info2) {
            cache('access_token2', null);
            $project_model = config('param.project_model');
            $project_model = Db::connect($this->dbconfig($info2['id']))->name('config')
                ->where('id', '=', 68)
                ->value('value');
            $array_cfg = preg_split('/[,;\r\n]+/', trim($project_model, ",;\r\n"));
            if (strpos($project_model, ':')) {
                $project_model = [];
                foreach ($array_cfg as $val) {
                    list($k, $v) = explode(':', $val);
                    $project_model[$k] = $v;
                }
            } else {
                $project_model = $project_model;
            }
            $tmid = Db::connect($this->dbconfig($info2['id']))->name('config')
                ->where('id', '=', 52)
                ->value('value');
            $list = Db::connect($this->dbconfig($info2['id']))->name('wx_msg')
                ->where('status', '=', 1)
                ->select();
            $run_info = Db::view('product_wx', 'authorizer_access_token')
                ->view('product_run', 'id,domain,diy_domain', 'product_wx.product_run_id=product_run.id')
                ->where('product_run.id', '=', $info2['id'])
                ->find();
            $data['access_token'] = $run_info['authorizer_access_token'];
            $domain = $run_info['diy_domain'] ? $run_info['diy_domain'] : $run_info['domain'];
            //dump($data['access_token']);
            //dump($list);
            foreach ($list as $item) {
                // dump($item);
                $user = DB::connect($this->dbconfig($info2['id']))->name('project_user')->where('project_id', $item['project_id'])->select();
                //dump($user);
                foreach ($user as $info) {
                    $openid = DB::connect($this->dbconfig($info2['id']))->name('admin')->where('id', $info['uid'])->value('openid');
                    if ($openid) {
                        $data['project_name'] = DB::connect($this->dbconfig($info2['id']))->name('project')->where('id', $item['project_id'])->value('title');
                        if ($item['model_id'] == 4) {
                            $data['model_name'] = '文档';
                        } else {
                            $data['model_name'] = $project_model[$item['model_id']];
                        }
                        //dump($data['model_name']);
                        $data['time'] = date('Y-m-d  H:i:s', $item['c_time']);
                        $data['openid'] = $openid;
                        if ($item['uid']) {
                            $data['nickname'] = '[操作人员:' . DB::connect($this->dbconfig($info2['id']))->name('admin')->where('id', $item['uid'])->value('nickname') . ']';
                        } else {
                            $data['nickname'] = '';
                        }
                        $data['info'] = $item['info'];
                        $data['uid'] = $info['uid'];
                        if ($item['model_id'] == 4) {
                            $data['status'] = '--';
                            $data['info_title'] = DB::connect($this->dbconfig($info2['id']))->name('doc')->where('id', $item['stories_id'])->value('title');
                            $data['url'] = 'https://' . $domain . '/wx/doc/index?id=' . $item['stories_id'];
                        } else {
                            // $status = config('param.model_' . $item['model_id'] . '_status');
                            switch ($item['model_id']) {
                                case 1:
                                    $cfg_id = 59;
                                    break;
                                case 2:
                                    $cfg_id = 62;
                                    break;
                                case 3:
                                    $cfg_id = 60;
                                    break;
                                default:
                                    $cfg_id = 59;

                            }
                            $status = DB::connect($this->dbconfig($info2['id']))->name('config')->where('id', $cfg_id)->value('value');
                            $array_cfg = preg_split('/[,;\r\n]+/', trim($status, ",;\r\n"));
                            if (strpos($status, ':')) {
                                $status = [];
                                foreach ($array_cfg as $val) {
                                    list($k, $v) = explode(':', $val);
                                    $status[$k] = $v;
                                }
                            } else {
                                $status = $status;
                            }

                            //dump($status);
                            //  dump( $status[$data['status']]);
                            //dump($item);

                            $data['status'] = $item['model_status'] ? $status[$item['model_status']] : '--';
                            $data['info_title'] = DB::connect($this->dbconfig($info2['id']))->name('stories')->where('id', $item['stories_id'])->value('title');
                            $data['url'] = 'https://' . $domain . '/wx/stories/index?stories_id=' . $item['stories_id'];
                        }
                        //dump($data);
                        $data['tmid'] = $tmid;
                        $data['msgid'] = $this->send($data);
                        $data['msg_id'] = $item['id'];
                        if ($data['msgid'] == 0) {
                            $data['status'] = 7;
                        } else {
                            $data['status'] = 2;
                        }
                        //exit;
                        DB::connect($this->dbconfig($info2['id']))->name('wx_msg_info')->strict(false)->insert($data);
                    }

                }
                DB::connect($this->dbconfig($info2['id']))->name('wx_msg')->where('id', $item['id'])->update(['status' => 2]);
            }
        }
    }

    protected function send($msg, $type = 1)
    {
        \think\facade\Log::write(json_encode($msg), 'INFO');
        //echo "access_token=" . cache('access_token2');
        $host = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $msg['access_token'];
        //$host = "https://openwx.weibuyun.com/auth/post2?access_token=" . $msg['access_token'];
        $sdata = array();
        if ($type == 1) {
            $sdata['template_id'] = $msg['tmid'];
            $sdata['touser'] = $msg['openid'];
            $sdata['url'] = $msg['url'];
            $data['first']['value'] = '你好,项目有新的变化' . $msg['nickname'];
            $data['first']['color'] = "#1E9FFF";
            $data['keyword1']['value'] = $msg['project_name'];
            $data['keyword1']['color'] = "#1E9FFF";
            $data['keyword2']['value'] = $msg['status'];
            $data['keyword2']['color'] = "#FFB800";
            $data['keyword3']['value'] = $msg['info_title'];
            $data['keyword3']['color'] = "#1E9FFF";
            $data['keyword4']['value'] = $msg['time'];
            $data['keyword4']['color'] = "#1E9FFF";
            $data['remark']['value'] = $msg['model_name'] . '发生变化:' . strip_tags($msg['info']);
            $data['remark']['color'] = "#FF5722";
        } else {
            $sdata['template_id'] = $msg['tmid'];
            $sdata['touser'] = $msg['openid'];
            $data['first']['value'] = '你好,项目财务有新的提醒';
            $data['first']['color'] = "#1E9FFF";
            $data['keyword1']['value'] = $msg['project_name'];
            $data['keyword1']['color'] = "#1E9FFF";
            $data['keyword2']['value'] = $msg['status'];
            $data['keyword2']['color'] = "#FFB800";
            $data['keyword3']['value'] = $msg['info_title'];
            $data['keyword3']['color'] = "#1E9FFF";
            $data['keyword4']['value'] = $msg['time'];
            $data['keyword4']['color'] = "#1E9FFF";
            $data['remark']['value'] = $msg['info'];
            $data['remark']['color'] = "#FF5722";
        }


        $sdata['data'] = $data;
        //dump($sdata);
//        echo config('param.domain');
        //dump($msg['tmid']);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $host);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($sdata));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $tmpInfo = curl_exec($ch);
        $re = json_decode($tmpInfo, TRUE);
        //dump($re);
        if (curl_errno($ch)) {
            //  dump(curl_error($ch));
            //  \Think\Log::write(json_encode(curl_errno($ch)), 'INFO');
            // \Think\Log::write(jcurl_errno($ch), 'INFO');
            // \think\facade\Log::write(json_encode(curl_errno($ch)), 'WX_MESSAGE_ERROE');
        }
        \think\facade\Log::write($re, 'WX_MESSAGE');
        // exit;
        curl_close($ch);
        if ($re['errcode'] == 0) {
            return $re['msgid'];
        } else {
            return 0;
        }

    }

    protected function stories($ulist)
    {
        list($start, $end) = Time::month();
        foreach ($ulist as $info) {

            $list = Db::connect($this->dbconfig($info['id']))->name('stories')
                ->where('s_time', '>=', $start)
                ->where('s_time', '<=', $end)
                ->select();
            foreach ($list as $item) {
                $data = array();
                $data['id'] = $item['id'];
                $w_time = DB::connect($this->dbconfig($info['id']))->name('work_time')
                    ->where('stories_id', $item['id'])
                    ->where('model_id', $item['model_id'])
                    ->where('uid', $item['touid'])
                    ->sum('w_time');
                DB::connect($this->dbconfig($info['id']))->name('stories')->where('id', $item['id'])->update(['w_time' => $w_time]);
            }
        }
    }

    protected function project($ulist)
    {
        foreach ($ulist as $info) {
            $list = Db::connect($this->dbconfig($info['id']))->name('project')
                ->where('status', '<>', 10)
                ->select();
            foreach ($list as $item) {
                $data = array();
                $data['id'] = $item['id'];
                $savedata['w_time'] = DB::connect($this->dbconfig($info['id']))->name('stories')
                    ->where('project_id', $item['id'])
                    ->sum('w_time');
                $savedata['p_time'] = DB::connect($this->dbconfig($info['id']))->name('stories')
                    ->where('project_id', $item['id'])
                    ->sum('p_time');
                $savedata['s_time'] = DB::connect($this->dbconfig($info['id']))->name('stories')
                    ->where('project_id', $item['id'])
                    ->min('s_time');
                $savedata['e_time'] = DB::connect($this->dbconfig($info['id']))->name('stories')
                    ->where('project_id', $item['id'])
                    ->max('e_time');
                DB::connect($this->dbconfig($info['id']))->name('project')->where('id', $item['id'])->update($savedata);
            }
        }
    }

    protected function user($ulist)
    {
        list($start, $end) = Time::month();
        /*用户工资核算*/

        foreach ($ulist as $info) {
            $list = Db::connect($this->dbconfig($info['id']))->name('auth_group_access')
                ->where('group_id', 'in', [11, 13])
                ->group('uid')
                ->select();//得出用户列表
//            dump($list);
//            exit;
            foreach ($list as $item) {
                //没有信息先建立信息
                $map['uid'] = $item['uid'];
                $map['m_time'] = $start;
                $month_wage = DB::connect($this->dbconfig($info['id']))->name('user_work')->where($map)->find();
                $user = DB::connect($this->dbconfig($info['id']))->name('user_base')->where('uid', $item['uid'])->find();
                //dump($month_wage);
                //计算本月出勤奖金
                $login_wage = DB::connect($this->dbconfig($info['id']))->name('workreg_d')
                    ->where('uid', $item['uid'])
                    ->where('d_time', '>=', $start)
                    ->where('d_time', '<=', $end)
                    ->where('wage_status', 2)
                    ->sum('work_wage');//汇总
                //dump($month_wage);
                //dump($login_wage);
                if ($month_wage) {
                    // 只更新出勤奖金和基本工资;
                    $data2['login_wage'] = $login_wage;
                    $data2['base_wage'] = $user['base_wage'];
                    $data2['sum_wage'] = $data2['base_wage'] + $data2['login_wage'] + $month_wage['change_wage'] + $month_wage['run_wage'];//
                    DB::connect($this->dbconfig($info['id']))->name('user_work')->where('id', $month_wage['id'])->update($data2);
                } else {
                    //新增
                    $data2['login_wage'] = $login_wage;//出勤
                    $data2['uid'] = $item['uid'];
                    $data2['m_time'] = $start;
                    $data2['change_wage'] = 0;//调整
                    $data2['base_wage'] = $user['base_wage'];//基本
                    $data2['run_wage'] = 0;//绩效
                    $data2['sum_wage'] = $data2['base_wage'] + $login_wage;
                    DB::connect($this->dbconfig($info['id']))->name('user_work')->insert($data2);
                }

                //计算用户本月应得项目绩效
                $project_list = DB::connect($this->dbconfig($info['id']))->view('project', 'id')
                    ->view('project_user', 'work_wage', 'project_user.project_id=project.id')
                    ->where('uid', $item['uid'])
                    ->select();//得出完成的项目
                // dump($project_list);
                foreach ($project_list as $item2) {
                    //计划时间，本月标记完成的
                    $data = [];
                    $data['p_time'] = Db::connect($this->dbconfig($info['id']))->name('stories')
                        ->where('status', 5)
                        ->where('touid', $item['uid'])
                        ->where('e_time', '>=', $start)
                        ->where('e_time', '<=', $end)
                        ->where('project_id', $item2['id'])
                        ->whereColumn('f_time', '<=', 'e_time')
                        ->sum('p_time');
                    $data['out_time'] = Db::connect($this->dbconfig($info['id']))->name('stories')
                        ->where('status', 5)
                        ->where('touid', $item['uid'])
                        ->where('f_time', '>=', $start)
                        ->where('f_time', '<=', $end)
                        ->where('project_id', $item2['id'])
                        ->whereColumn('f_time', '>', 'e_time')
                        ->sum('p_time');
                    $data['uid'] = $item['uid'];
                    $data['m_time'] = $start;
                    $data['project_id'] = $item2['id'];
                    $work_wage = $user['work_wage'];//小时绩效
                    $data['run_wage'] = $work_wage * $data['p_time'];//得
                    $data['out_wage'] = $work_wage * $data['out_time'];//扣
                    $data['work_wage'] = $work_wage;//绩效标准
                    $map3 = [];
                    $map3['uid'] = $data['uid'];
                    $map3['m_time'] = $data['m_time'];
                    $map3['project_id'] = $data['project_id'];
                    if ($data['run_wage']) {
                        if (DB::connect($this->dbconfig($info['id']))->name('project_work')->where($map3)->find()) {
                            //echo 1;
                            $data4 = [];
                            $data4['run_wage'] = $data['run_wage'];
                            $data4['out_wage'] = $data['out_wage'];
                            $data4['work_wage'] = $data['work_wage'];
                            DB::connect($this->dbconfig($info['id']))->name('project_work')->where($map3)->update($data4);//存入项目明细
                        } else {
                            dump($data);
                            DB::connect($this->dbconfig($info['id']))->name('project_work')->insert($data);//存入项目明细
                        }

                        //项目财务处理
                        $map5 = [];
                        $map5['project_id'] = $item2['id'];
                        $map5['c_time'] = $start;
                        $map5['uid'] = $item['uid'];
                        $map5['project_financial'] = 5;//人工
                        $map5['financial_type'] = 2;//支付

                        if (DB::connect($this->dbconfig($info['id']))->name('project_financial')->where($map5)->find()) {
                            $data3 = [];
                            $data3['info'] = date('m', $start) . '月开发人员绩效核算';
                            $data3['price'] = $data['run_wage'];
                            // dump(DB::connect($this->dbconfig($info['id']))->name('project_financial')->where($map5)->find());
                            DB::connect($this->dbconfig($info['id']))->name('project_financial')->where($map5)->update($data3);
                        } else {
                            $map5['info'] = date('m', $start) . '月开发人员绩效核算';
                            $map5['price'] = $data['run_wage'];
                            //dump($map5);
                            DB::connect($this->dbconfig($info['id']))->name('project_financial')->insert($map5);
                        }

                        if (DB::connect($this->dbconfig($info['id']))->name('project_financial')->where('project_id', $item2['id'])->where('financial_type', 0)->find()) {
                            //什么也不做
                        } else {
                            $data4 = [];
                            $data4['c_time'] = 0;
                            $data4['uid'] = $item['uid'];
                            $data4['info'] = '毛利=收入-支出+应收-应付；CLI';
                            $data4['project_financial'] = 8;
                            $data4['financial_type'] = 0;//标记为毛利
                            $data4['price'] = 0;
                            $data4['project_id'] = $item2['id'];
                            DB::connect($this->dbconfig($info['id']))->name('project_financial')->insert($data4);
                            // echo  DB::connect($this->dbconfig($info['id']))->name('project_financial')->insertGetId($data4);
                        }
                        //计算毛利
                        $type1 = DB::connect($this->dbconfig($info['id']))->name('project_financial')->where('financial_type', '>', 0)->where('project_id', $item2['id'])->where('financial_type', 1)->sum('price');
                        $type2 = DB::connect($this->dbconfig($info['id']))->name('project_financial')->where('financial_type', '>', 0)->where('project_id', $item2['id'])->where('financial_type', 2)->sum('price');
                        $type3 = DB::connect($this->dbconfig($info['id']))->name('project_financial')->where('financial_type', '>', 0)->where('project_id', $item2['id'])->where('financial_type', 3)->sum('price');
                        $type4 = DB::connect($this->dbconfig($info['id']))->name('project_financial')->where('financial_type', '>', 0)->where('project_id', $item2['id'])->where('financial_type', 4)->sum('price');
                        DB::connect($this->dbconfig($info['id']))->name('project_financial')->where('project_id', $item2['id'])->where('financial_type', 0)->update(['price' => $type1 - $type2 + $type3 - $type4]);
                    }
                }
                //本月工资增加
                $map3 = [];
                $map3['uid'] = $data['uid'];
                $map3['m_time'] = $data['m_time'];
                $run_wage = DB::connect($this->dbconfig($info['id']))->name('project_work')->where($map3)->sum('run_wage');
                if ($run_wage) {

                   // dump($map3);
                    //dump($run_wage);
                    $month_wage = DB::connect($this->dbconfig($info['id']))->name('user_work')->where($map3)->find();
                    $data21 = [];
                    $data21['run_wage'] = $run_wage;
                    $data21['sum_wage'] = $data21['run_wage'] + $month_wage['base_wage'] + $month_wage['login_wage'] + $month_wage['change_wage'];
                    //dump($month_wage);
                   // dump($data21);
                    DB::connect($this->dbconfig($info['id']))->name('user_work')->where('id', $month_wage['id'])->update($data21);
                }
            }
        }

    }

    function parse($str)
    {
        $array = preg_split('/[,;\r\n]+/', trim($str, ",;\r\n"));
        if (strpos($str, ':')) {
            $str = [];
            foreach ($array as $val) {
                list($k, $v) = explode(':', $val);
                $str[$k] = $v;
            }
        } else {
            $str = $array;
        }
        return $str;
    }

    protected function login_wage($ulist)
    {
        /*用户日时间核算*/
        list($s_day, $e_day) = Time::yesterday();

        $map['d_time'] = $s_day;
        foreach ($ulist as $info) {
            $list = DB::connect($this->dbconfig($info['id']))->name('workreg_d')
                ->where($map)
                ->select();
            //数据库取出变成数组82
            $login_time = DB::connect($this->dbconfig($info['id']))->name('config')->where('id', 82)->value('value');
            $login_time = $this->parse($login_time);
            //1:考勤表建立
            //2:请事假
            //3:节假日
            //4:正常考勤
            //5:周六日
            //6:请病假
            //7:其他假

            foreach ($list as $item) {
                //dump($item);
                $user = DB::connect($this->dbconfig($info['id']))->name('user_base')->where('uid', $item['uid'])->find();
                $data = [];
                switch ($item['status']) {
                    case 2:
                        //事假
                        $data['work_wage'] = $user['leave_wage'];
                        break;
                    case 6:
                        //病假
                        $data['work_wage'] = $user['sick_wage'];
                        break;
                    case 4:
                        //正常
                        $data['work_wage'] = $user['day_wage'];
                        $am_in = strtotime(date('Ymd' . $login_time[1] . '59', $item['am_in']));
                        // echo date('Ymd' . $login_time[1] . '59', $item['am_in']);
                        $wage = 0;
                        if ($item['am_in'] > 0 && $item['am_in'] <= $am_in) {
                            $wage = $wage + $user['login_wage'];
                        }
                        $am_out = strtotime(date('Ymd  ' . $login_time[2] . '00', $item['am_out']));
                        if ($item['am_out'] > 0 && $item['am_out'] >= $am_out) {
                            $wage = $wage + $user['login_wage'];
                        }
                        $fm_in = strtotime(date('Ymd  ' . $login_time[3] . '59', $item['fm_in']));
                        if ($item['fm_in'] > 0 && $item['fm_in'] <= $fm_in) {
                            $wage = $wage + $user['login_wage'];
                        }
                        $fm_out = strtotime(date('Ymd  ' . $login_time[4] . '00', $item['fm_out']));
                        if ($item['fm_out'] > 0 && $item['fm_out'] >= $fm_out) {
                            $wage = $wage + $user['login_wage'];
                        }
                        $data['work_wage'] = $data['work_wage'] + $wage;
                        break;
                    default:
                        $data['work_wage'] = 0;
                }
                $data['wage_status'] = 2;
                DB::connect($this->dbconfig($info['id']))->name('workreg_d')->where('id', $item['id'])->update($data);
                //dump($data);
            }
        }
    }

    protected function day_user($ulist)
    {
        /*用户日时间核算*/
        list($s_day, $e_day) = Time::today();
        foreach ($ulist as $info2) {
            $list = Db::connect($this->dbconfig($info2['id']))->name('auth_group_access')
                ->where('group_id', '=', 11)
                ->select();
            foreach ($list as $item) {
                $map['uid'] = $item['uid'];
                $map['c_time'] = $s_day;
                $info = DB::connect($this->dbconfig($info2['id']))->name('work_user_time')
                    ->where($map)
                    ->find();
                $data['w_time'] = Db::connect($this->dbconfig($info2['id']))->name('work_time')
                    ->where('c_time', '>=', $s_day)
                    ->where('c_time', '<=', $e_day)
                    ->where('uid', $item['uid'])
                    ->sum('w_time');
                $data['w_time'] = $data['w_time'];//转化成小时
                $data['model_1'] = Db::connect($this->dbconfig($info2['id']))->name('work_time')
                    ->where('c_time', '>=', $s_day)
                    ->where('c_time', '<=', $e_day)
                    ->where('uid', $item['uid'])
                    ->where('model_id', 1)
                    ->count();
                $data['model_2'] = Db::connect($this->dbconfig($info2['id']))->name('work_time')
                    ->where('c_time', '>=', $s_day)
                    ->where('c_time', '<=', $e_day)
                    ->where('model_id', 2)
                    ->where('uid', $item['uid'])
                    ->count();
                $data['model_3'] = Db::connect($this->dbconfig($info2['id']))->name('work_time')
                    ->where('c_time', '>=', $s_day)
                    ->where('c_time', '<=', $e_day)
                    ->where('model_id', 3)
                    ->where('uid', $item['uid'])
                    ->count();
                if ($info) {
                    DB::connect($this->dbconfig($info2['id']))->name('work_user_time')->where($map)->update($data);
                } else {
                    $data['uid'] = $item['uid'];
                    $data['c_time'] = $s_day;
                    DB::connect($this->dbconfig($info2['id']))->name('work_user_time')->insert($data);
                }
            }
        }
    }

    protected function work_time($ulist)
    {
        list($s_day, $e_day) = Time::month();
        foreach ($ulist as $info2) {
            $list = Db::connect($this->dbconfig($info2['id']))->name('auth_group_access')
                ->where('group_id', '=', 11)
                ->select();
            //dump($list);
            foreach ($list as $item) {
                $map['uid'] = $item['uid'];
                $map['m_time'] = $s_day;
                $info = DB::connect($this->dbconfig($info2['id']))->name('user_work')
                    ->where($map)
                    ->find();
                //得到当前人员的需求时间
//                $data['work_time'] = Db::connect($this->dbconfig($info2['id']))->name('work_time')
//                    ->where('c_time', '>=', $s_day)
//                    ->where('c_time', '<=', $e_day)
//                    ->where('uid', $item['uid'])
//                    ->where('model_id', 1)
//                    ->sum('w_time');
                $data['work_time'] = Db::connect($this->dbconfig($info2['id']))->name('stories')
                    ->where('s_time', '>=', $s_day)
                    ->where('e_time', '<=', $e_day)
                    ->where('touid', $item['uid'])
                    ->where('model_id', 1)
                    ->sum('p_time');
                if ($info) {
                    DB::connect($this->dbconfig($info2['id']))->name('user_work')->where($map)->update($data);
                }
            }
        }
    }

}